<?php
declare (strict_types=1);

namespace app\middleware\coupon_order;

use app\model\AgentSupplier;
use think\Exception;

class CheckAgentJutuikeChannelPremission
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     */
    public function handle($request, \Closure $next)
    {

        $jutuike = self::matchChannel();

        if (empty($jutuike)) {
            throw new Exception('未配置渠道:  22511');
        }

        $agent_id = $request->agentChannel['agent_id'];

        $supplier_id = $jutuike->supplierInfo->id;

        $agentSupplier = AgentSupplier::where([
            'agent_id' => $agent_id,
            'supplier_id' => $supplier_id,
            'serv_type' => $jutuike->supplierInfo->serv_type,
        ])->find();

        if (!$agentSupplier) {
            return fail('渠道未申请，请联系管理员');
        }

        return $next($request);
    }

    /**
     * @return \api\channel\jutuike\Coupon|\api\channel\jutuike\FoodUnion|\api\channel\jutuike\TravelUnion|mixed|string|\think\response\Json
     */
    public static function matchChannel(){

        $action = request()->action();
        $jutuike = '';
        switch ($action) {
            case 'getUnionUrl':
                $act_id = input('act_id');//默认联联周边游

                if (empty($act_id)) {
                    return fail('未配置活动');
                }
                $acts = [
                    54 => new \api\channel\jutuike\AroundUnion(),
                    58 => new \api\channel\jutuike\TravelUnion(),
                ];
                $jutuike = $acts[$act_id] ?? new \api\channel\jutuike\TravelUnion();//默认都是出行加油，以后再说咯
                //单独判断
                break;
            case 'getFoodJumpUrl':
                $jutuike = new \api\channel\jutuike\FoodUnion();
                break;
            case 'getJumpUrlByTravelId':
                $jutuike = new \api\channel\jutuike\TravelUnion();
                break;
            case 'getJumpUrlByBrandId'://权益
                $jutuike = new \api\channel\jutuike\Coupon();
                break;

        }

        return  $jutuike;

    }
}
